package com.gan.bi.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gan.bi.annotation.AuthCheck;
import com.gan.bi.common.BaseResponse;
import com.gan.bi.common.DeleteRequest;
import com.gan.bi.common.ErrorCode;
import com.gan.bi.common.ResultUtils;
import com.gan.bi.constant.FileConstant;
import com.gan.bi.constant.UserConstant;
import com.gan.bi.exception.BusinessException;
import com.gan.bi.exception.ThrowUtils;
import com.gan.bi.manager.AiManager;
import com.gan.bi.manager.RedisLimiterManager;
import com.gan.bi.model.dto.chart.*;
import com.gan.bi.model.entity.Chart;
import com.gan.bi.model.entity.User;
import com.gan.bi.model.enums.ChartStatusEnum;
import com.gan.bi.model.enums.FileUploadBizEnum;
import com.gan.bi.model.vo.BIResponse;
import com.gan.bi.rabbitmq.BiMessageProducer;
import com.gan.bi.service.ChartService;
import com.gan.bi.service.UserService;
import com.gan.bi.utils.ExcelUtils;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.asn1.cms.PasswordRecipientInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 帖子接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@RestController
@RequestMapping("/chart")
@Slf4j
public class ChartController {

    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;

    @Resource
    private AiManager aiManager;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private RedisLimiterManager redisLimiterManager;

    @Resource
    private BiMessageProducer biMessageProducer;

    private final static Gson GSON = new Gson();

    // region 增删改查

    /**
     * 创建
     *
     * @param chartAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addChart(@RequestBody ChartAddRequest chartAddRequest, HttpServletRequest request) {
        if (chartAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartAddRequest, chart);
        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());
        boolean result = chartService.save(chart);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newChartId = chart.getId();
        return ResultUtils.success(newChartId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteChart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldChart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = chartService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param chartUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateChart(@RequestBody ChartUpdateRequest chartUpdateRequest) {
        if (chartUpdateRequest == null || chartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartUpdateRequest, chart);
        long id = chartUpdateRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<Chart> getChartVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = chartService.getById(id);
        if (chart == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(chart);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<Chart>> listChartVOByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                       HttpServletRequest request) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                chartService.getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<Chart>> listMyChartVOByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                         HttpServletRequest request) {
        if (chartQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        chartQueryRequest.setUserId(loginUser.getId());
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                chartService.getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }


    /**
     * 编辑（用户）
     *
     * @param chartEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editChart(@RequestBody ChartEditRequest chartEditRequest, HttpServletRequest request) {
        if (chartEditRequest == null || chartEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartEditRequest, chart);
        User loginUser = userService.getLoginUser(request);
        long id = chartEditRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldChart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 智能分析线程池异步版
     *
     * @param multipartFile
     * @param genChartByAIRequest
     * @param request
     * @return
     */
    @PostMapping("/gen/async")
    public BaseResponse<BIResponse> genChartByAiAsync(@RequestPart("file") MultipartFile multipartFile,
                                            GenChartByAIRequest genChartByAIRequest, HttpServletRequest request) {

        BIResponse biResponse = new BIResponse();
        // ai 模型编号
        Long modelId = 1659171950288818178L;
        String goal = genChartByAIRequest.getGoal();
        String name = genChartByAIRequest.getName();
        String chartType = genChartByAIRequest.getChartType();
        // 参数校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal),new BusinessException(411,"分析目标不能为空"));
        ThrowUtils.throwIf(StringUtils.isNotBlank(name) && name.length() > 100,ErrorCode.PARAMS_ERROR,"名称过长!");
        // 校验文件
        String fileName = multipartFile.getOriginalFilename();
        long fileSize = multipartFile.getSize();
        final long ONE_MB = 1024 * 1024L;
        ThrowUtils.throwIf(fileSize > ONE_MB,ErrorCode.PARAMS_ERROR,"文件超过1MB!");
        // 校验文件后缀
        String suffix = FileUtil.getSuffix(fileName);
        final List<String> validExcelSuffix = Arrays.asList("xls","xlsx");
        ThrowUtils.throwIf(!validExcelSuffix.contains(suffix), ErrorCode.PARAMS_ERROR,"文件后缀非法!");

        // 限流,使用业务前缀去区分开不同的限流器
        redisLimiterManager.doRateLimit("genChartByAI" + String.valueOf(userService.getLoginUser(request).getId()));

        // 拿到压缩后的数据
        String csvFile = ExcelUtils.excelToCSV(multipartFile);
        // 拼接用户输入的内容
        StringBuilder userInput = new StringBuilder();
        // 系统预设，已经写在了 鱼聪明上面了，这边不需要在传递一遍
//        final String systemDefault = "你是一名数据分析师和前端开发专家，接下来我会按照以下固定格式给你提供内容:\n" +
//                "分析需求:\n{数据分析的需求或者目标}\n原始数据:\n{csv 格式的原始数据，用,作为分隔符}\n请根据以上内容，帮我生成数据分析结论和可视化图表代码（此外不要生成任何多余的开头，结尾，注释等内容）\n"
//                 + "+++++\n{前端 Echarts V5 的 Option 配置对象 js 代码，合理地将数据进行可视化}\n" + "+++++\n{图表的描述，以及明确的数据分析结论、越详细越好，且不要生成任何注释内容}\n";

        // "分析需求：\n分析网站用户增长情况\n原始数据：\n日期,用户数\n1号,10\n2号,20\n3号,30\n"
        userInput.append("分析需求：\n" + goal + "\n");
        if (StringUtils.isNotBlank(chartType)){
            userInput.append("请使用:" + chartType + "\n");
        }
        userInput.append("原始数据:\n" + csvFile);

        // 先插入数据到数据库中，这样用户就可以实时看到这张图表了，哪怕它正在生成中
        Chart chart = new Chart();
        chart.setGoal(goal);
        chart.setName(name);
        chart.setChartData(csvFile);
        chart.setChartType(chartType);
        chart.setStatus(ChartStatusEnum.WAITING.getValue());
        chart.setUserId(userService.getLoginUser(request).getId());
        boolean flag = chartService.save(chart);
        if (!flag){
            handleChartUpdateError(chart.getId(), "数据库保存失败!");
            throw new BusinessException(455,"数据库保存失败!");
        }


        // 使用自定义的线程池异步调用 AI 接口
        CompletableFuture.runAsync(() -> {
            Chart updateChart = new Chart();
            updateChart.setStatus(ChartStatusEnum.RUNNING.getValue());
            updateChart.setId(chart.getId());
            String answer = null;
            try {
                answer = aiManager.doChat(modelId, userInput.toString());
            } catch (Exception e) {
                handleChartUpdateError(updateChart.getId(), "调用 AI 接口失败!");
                throw new BusinessException("调用 AI 接口失败!");
            }
            // 拆分回答
            String[] split = answer.split("【【【【【");
            if (split.length >= 4){
                handleChartUpdateError(chart.getId(), "ai 返回错误!");
                throw new BusinessException(ErrorCode.SYSTEM_ERROR,"ai 返回错误!");
            }

            String genChart = split[1];
            String genResult = split[2];
            updateChart.setStatus(ChartStatusEnum.SUCCEED.getValue());
            updateChart.setGenChart(genChart);
            updateChart.setGenResult(genResult);
            chartService.updateById(updateChart);

            biResponse.setChartId(updateChart.getId());
            biResponse.setGenChart(genChart);
            biResponse.setGenResult(genResult);
        },threadPoolExecutor);

        return ResultUtils.success(biResponse);

    }


    /**
     * 智能分析消息队列版
     *
     * @param multipartFile
     * @param genChartByAIRequest
     * @param request
     * @return
     */
    @PostMapping("/gen/async/mq")
    public BaseResponse<BIResponse> genChartByAiMq(@RequestPart("file") MultipartFile multipartFile,
                                                      GenChartByAIRequest genChartByAIRequest, HttpServletRequest request) {

        BIResponse biResponse = new BIResponse();
        String goal = genChartByAIRequest.getGoal();
        String name = genChartByAIRequest.getName();
        String chartType = genChartByAIRequest.getChartType();
        // 参数校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal),new BusinessException(411,"分析目标不能为空"));
        ThrowUtils.throwIf(StringUtils.isNotBlank(name) && name.length() > 100,ErrorCode.PARAMS_ERROR,"名称过长!");
        // 校验文件
        String fileName = multipartFile.getOriginalFilename();
        long fileSize = multipartFile.getSize();
        final long ONE_MB = 1024 * 1024L;
        ThrowUtils.throwIf(fileSize > ONE_MB,ErrorCode.PARAMS_ERROR,"文件超过1MB!");
        // 校验文件后缀
        String suffix = FileUtil.getSuffix(fileName);
        final List<String> validExcelSuffix = Arrays.asList("xls","xlsx");
        ThrowUtils.throwIf(!validExcelSuffix.contains(suffix), ErrorCode.PARAMS_ERROR,"文件后缀非法!");

        // 限流,使用业务前缀去区分开不同的限流器
        redisLimiterManager.doRateLimit("genChartByAI" + String.valueOf(userService.getLoginUser(request).getId()));

        // 拿到压缩后的数据
        String csvFile = ExcelUtils.excelToCSV(multipartFile);


        // 先插入数据到数据库中，这样用户就可以实时看到这张图表了，哪怕它正在生成中
        Chart chart = new Chart();
        chart.setGoal(goal);
        chart.setName(name);
        chart.setChartData(csvFile);
        chart.setChartType(chartType);
        chart.setStatus(ChartStatusEnum.WAITING.getValue());
        chart.setUserId(userService.getLoginUser(request).getId());
        boolean flag = chartService.save(chart);
        if (!flag){
            handleChartUpdateError(chart.getId(), "数据库保存失败!");
            throw new BusinessException(455,"数据库保存失败!");
        }

        long id = chart.getId();

        // 将消息发送到消息队列中
        biMessageProducer.sendMessage(String.valueOf(id));

        return ResultUtils.success(biResponse);

    }

    /**
     * 处理执行失败时的回调
     * @param chartId
     * @param execMessage
     */
    private void handleChartUpdateError(long chartId,String execMessage){
        Chart chart = new Chart();
        chart.setId(chartId);
        chart.setStatus(ChartStatusEnum.FILED.getValue());
        chart.setExecMessage(execMessage);
        if (!chartService.updateById(chart)){
            log.error("执行失败时，修改图表信息失败!");
        }
    }

}
